﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Planer.Model.Validators;

namespace Planer.Model
{
    public class AllocationTransactionModel
    {
        static AllocationTransactionModel model = null;

        protected AllocationTransactionModel()
        {            
        }

        public static AllocationTransactionModel GetInstance()
        {
            if (model == null)
            {
                model = new AllocationTransactionModel();
            }

            return model;
        }

        public allocation_transanction GetLastTransactionByAllocation(allocation Allocation)
        {
            var query = from trans in Program.Db.allocation_transanction
                         where trans.allocation.id == Allocation.id
                         orderby trans.create_date descending
                         select trans;
            if (query.Count<allocation_transanction>() == 0)
                return null;
            return query.First<allocation_transanction>();
                        
        }

        public List<allocation_transanction> GetTransactionListForGoalsByAllocation(allocation Allocation)
        {
            period p = PeriodModel.GetInstance().GetCurrentPeriod();
            var query = from trans in Program.Db.allocation_transanction
                        where trans.allocation.id == Allocation.id
                               && trans.allocation.accumulation == null
                                && trans.period.id == p.id 
                        orderby trans.create_date descending
                        select trans;
            return query.ToList<allocation_transanction>();

        }

        public ModelResult SaveOrUpdatePeriodicalAllocationTransaction(allocation_transanction Transaction)
        {
            //validate !!!!
            
            if (Transaction.id == 0)
            {
                Program.Db.AddToallocation_transanction(Transaction);
            }

            Program.Db.SaveChanges();

            return new ModelResult();
        }
    }
}
